package com.smart.manager.pop.repository;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import com.smart.common.entities.core.Page;
import com.smart.manager.pop.entities.assembler.IncludeData;
import com.smart.manager.pop.entities.body.RPopExchange;
import com.smart.manager.pop.entities.enums.CDKState;
import com.smart.manager.pop.entities.enums.ExchangeKind;
import com.smart.manager.pop.entities.models.PopDisExchange;
import com.smart.manager.pop.entities.models.query.QPopDisExchange;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 支付中心-订单管理
 *
 * @author Administrator
 */

@Log4j2
@Service
@RequiredArgsConstructor
public class PopExchangeRepository {


    private static final String CHARACTERS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // 去掉易混淆的字符
    private static final int CODE_LENGTH = 10;
    private static final int MAX_TRIES = 10000; // 最大尝试次数，用于避免无限循环

    public Page<PopDisExchange> pageList(RPopExchange.SearchBody search) {

        QPopDisExchange query = new QPopDisExchange();
        Opt.ofBlankAble(search.getRedeemCodes()).ifPresent(x -> query.redeemCodes.contains(x));
        Opt.ofBlankAble(search.getState()).ifPresent(x -> query.state.eq(x));
        Opt.ofBlankAble(search.getKind()).ifPresent(x -> query.kind.eq(x));
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows()).order().id.desc();
        return new Page<PopDisExchange>().load(query.findPagedList());
    }

    /**
     * 添加
     *
     * @param form 形式
     */
    @Async
    public void add(RPopExchange.GenerationBody form) {
        Set<String> strings = generateUniqueCDKs(form.getNumber());
        List<PopDisExchange> exchanges = new ArrayList<>();
        strings.forEach(x->{
            PopDisExchange popDisExchange = new PopDisExchange().setKind(form.getKind()).setState(CDKState.NOT).setProportion(form.getProportion()).setRedeemCodes(x);
            if (form.getKind().equals(ExchangeKind.PIG)){
                popDisExchange.setProportion(BigDecimal.ONE).setIncludeContent(new IncludeData().setMonths(form.getMonths()).setPigGoodsCode(form.getPigGoodsCode()));
            }
            exchanges.add(popDisExchange);
        });
        DB.insertAll(exchanges);
    }

    public static Set<String> generateUniqueCDKs(int count) {
        Set<String> generatedCodes = new HashSet<>();
        SecureRandom random = new SecureRandom();
        int tries = 0;

        while (generatedCodes.size() < count && tries < MAX_TRIES) {
            StringBuilder cdkCode = new StringBuilder();
            for (int i = 0; i < CODE_LENGTH; i++) {
                int index = random.nextInt(CHARACTERS.length());
                cdkCode.append(CHARACTERS.charAt(index));
            }
            String generatedCode = cdkCode.toString();
            generatedCodes.add(generatedCode);
            tries++;
        }
        Assert.isFalse(tries == MAX_TRIES && generatedCodes.size() < count,"生成的兑换码超出限制请重新尝试!");
        return generatedCodes;
    }

    /**
     * 批量删除
     *
     * @param idList id列表
     * @return int
     */
    public int delByIds(List<Long> idList) {
        long count = new QPopDisExchange().id.in(idList).findStream().count();
//        Assert.isTrue(count == 0, "操作失败:存在已有数据的客户经理账号");
        return DB.deleteAll(PopDisExchange.class, idList);
    }


    public PopDisExchange getOneById(Long managerId) {
        PopDisExchange record = new QPopDisExchange().id.eq(managerId).findOne();
        Assert.notNull(record, "客户经理信息不存在");
        return record;
    }
}
